<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { categoryApi } from '@/api/category'
import type { CategoryVO } from '@/types'
import { useRouter } from 'vue-router'
import { useToast } from '@/components/ui/toast'

const router = useRouter()
const toast = useToast()
const categories = ref<CategoryVO[]>([])
const categoryInput = ref('')
const loading = ref(false)

onMounted(() => {
  loadCategories()
})

const loadCategories = async () => {
  loading.value = true
  try {
    const res = await categoryApi.getList()
    if (res.data.code === 200) {
      categories.value = res.data.data
    } else {
      toast.error('加载分类失败：' + res.data.msg)
    }
  } catch (err) {
    toast.error('加载分类失败')
  } finally {
    loading.value = false
  }
}

const handleAddCategories = async () => {
  if (!categoryInput.value.trim()) {
    toast.warning('分类名称不能为空')
    return
  }

  const names = categoryInput.value
    .split(',')
    .map((name) => name.trim())
    .filter((name) => name.length > 0)

  if (names.length === 0) {
    toast.warning('请输入有效的分类名称')
    return
  }

  loading.value = true
  try {
    const res = await categoryApi.batchAdd(names)
    if (res.data.code === 200) {
      toast.success('添加分类成功')
      categoryInput.value = ''
      // 重新加载分类列表
      await loadCategories()
    } else {
      toast.error('添加分类失败：' + res.data.msg)
    }
  } catch (err) {
    toast.error('添加分类失败')
  } finally {
    loading.value = false
  }
}

const handleCategoryClick = (categoryId: number) => {
  router.push({
    path: '/articles',
    query: { categoryId: categoryId.toString() },
  })
}
</script>

<template>
  <div class="container mx-auto px-4 py-8 mt-16">
    <div class="max-w-4xl mx-auto">
      <div class="flex items-center justify-between mb-8">
        <h1 class="text-2xl font-bold">分类管理</h1>
      </div>

      <!-- 添加分类表单 -->
      <div class="space-y-4 mb-8">
        <div class="flex gap-4">
          <input
            v-model="categoryInput"
            type="text"
            placeholder="输入分类名称，多个分类用英文逗号分隔"
            class="flex-1 h-10 px-3 py-2 text-sm rounded-md border border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
            @keyup.enter="handleAddCategories"
          />
          <button
            @click="handleAddCategories"
            :disabled="loading"
            class="inline-flex items-center justify-center h-10 px-4 py-2 text-sm font-medium text-primary-foreground bg-primary rounded-md ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 hover:bg-primary/90"
          >
            {{ loading ? '添加中...' : '批量添加' }}
          </button>
        </div>
        <p class="text-sm text-muted-foreground">提示：可以输入多个分类名称，用英文逗号（,）分隔</p>
      </div>

      <!-- 分类列表 -->
      <div class="bg-card text-card-foreground rounded-lg border shadow-sm">
        <div class="p-6">
          <div v-if="loading" class="flex justify-center py-8">
            <div
              class="animate-spin rounded-full h-8 w-8 border-4 border-primary border-t-transparent"
            ></div>
          </div>
          <div v-else-if="categories.length === 0" class="py-8 text-center text-muted-foreground">
            暂无分类
          </div>
          <div v-else class="flex flex-wrap gap-3">
            <div
              v-for="category in categories"
              :key="category.id"
              @click="handleCategoryClick(category.id)"
              class="group relative inline-flex items-center rounded-full border px-4 py-2 text-sm font-semibold transition-colors hover:bg-muted focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 cursor-pointer"
            >
              {{ category.categoryName }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
